/**
 * created by xuqiang 19/05/08
 * http配置
 */
import axios from 'axios'
import {Message} from 'element-ui'
import local from '../global/local'


// http request 拦截器
class httpRequest {
    constructor () {
        this.options = {
            url: '',
            method: ''
        };
        // 存储请求队列
        this.queue = {}
    }

    // 销毁请求实例
    destroy (url) {
        delete this.queue[url];
        const queue = Object.keys(this.queue);
        return queue.length
    }

    // 请求拦截
    interceptors (instance, url) {
        // request拦截器
        instance.interceptors.request.use(
            config => {
                if (local.getToken()) {
                    config.headers['token'] = local.getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
                }
                config.headers['Content-Type'] = 'application/json';
                config.validateStatus = (status) => {
                    return status >= 200 && status <= 500;
                };
                return config
            },
            error => {
                return Promise.reject(error)
            }
        );

        // response 拦截器
        instance.interceptors.response.use(
            response => {
                this.destroy(url);
                const res = response.data;
                switch (response.status) {
                    // 操作完成
                    case 200:
                        if (res.message !== '成功') {
                            /*Message({
                                type: 'success',
                                message: res.message,
                            })*/
                        }
                        break;
                    // 创建成功
                    case 201:
                        Message({
                            type: 'success',
                            message: res.message || '创建成功',
                        })
                        break;
                    // 接收到请求，挂起（不常用）
                    case 202:
                        break;
                    // 表单验证错误
                    case 400:
                        Message({
                            type: 'error',
                            message: res.message || '表单验证错误',
                        })
                        break;
                    // TOKEN过期或未登录
                    case 401:
                        Message({
                            type: 'error',
                            message: res.message || '未登录，或登录失效，请登录!',
                        })
                        break;
                    case 403:
                        Message({
                            type: 'error',
                            message: res.message || '您本次请求未授权!',
                        })
                        break;
                    case 404:
                        Message({
                            type: 'error',
                            message: res.message || '该资源不存在',
                        })
                        break;
                    default:
                        Message({
                            type: 'error',
                            message: res.message || '未知错误',
                        })
                }
                return res;
            },
            error => {
                Message({
                    message: '遇到未知错误或网络错误，请检查网络连接或联系管理员',
                    type: 'error',
                    duration: 5 * 1000
                });
                return Promise.reject(error)
            }
        );
    }

    // 创建实例
    create (baseUrl) {
        let conf = {
            baseURL: baseUrl,
            timeout: 2000,
            headers: {
                'Content-Type': 'application/json; charset=utf-8',
                // 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
                // 标识为ajax请求
                'X-Requested-With': 'XMLHttpRequest',
                'Terminal-Type': 'vue_ui'
            },
            // 携带认证信息，默认为false，这样在跨域请求下session无法获取信息
            withCredentials: true
        };
        return axios.create(conf)
    }
    // 请求实例
    request (baseUrl,options) {
        let  instance = this.create(baseUrl);
        this.interceptors(instance, options.url);
        options = Object.assign({}, options);
        this.queue[options.url] = instance;
        return instance(options)
    }
}
export default httpRequest
